package com.ghostflying.cameraonfly;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;



import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity implements SurfaceHolder.Callback,Camera.PictureCallback,Camera.PreviewCallback {
	
	static boolean DEBUG=true;
	static String TAG="Main Activity";
	public static final int BLUETOOTH_GET = 0;
	public static final int COMMAND_GET = 1;
	public static final int CONNECT_TO_TABLET_SUCC = 2;
	public static final int CONNECT_TO_TABLET_VIDEO_SUCC = 4;
	public static final int CONNECT_TO_DSP_SUCC = 3;
	public static final int VIDEO_DISCONNECT = 11;
	public static final int CONTROL_DISCONNECT = 5;
	private SurfaceView mSurfaceView=null;
	private Camera mCamera=null;
	private SurfaceHolder mSurfaceHolder = null;
	private NetworkService mNetwork=null;
	private ControlNetworkService mControlNetwork=null;
	private BluetoothService mBluetoothService = null;
	private int sendFlag = 0;
	private Button ConnectDSP=null;
	private Button ConnectTablet=null;
	private Button ConnectVideo=null;
	private Button Debug=null;
	private EditText ipaddText = null;
	private String BluetoothDeviceAddress="20:13:09:05:22:79";//�����豸��ַ
	private BluetoothAdapter mBluetoothAdapter = null;//����������
	//private ProgressImage mProgressImage=null;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initCamera();
		//mNetwork=new NetworkService();
		//mNetwork.Connect("192.168.1.110", 5174);
		ipaddText = (EditText)findViewById(R.id.ipadd);
		ConnectDSP= (Button)findViewById(R.id.dsp);		
		ConnectDSP.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		    	if (!mBluetoothAdapter.isEnabled()) {
		            //Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);		//��ʾ������
		            mBluetoothAdapter.enable();//������
		            Toast.makeText(getApplicationContext(), "Bluetooth is opening ,please press the button soon.", Toast.LENGTH_SHORT).show();
		         // Otherwise, setup the chat session
		        } else {
		            if (mBluetoothService == null) {
		            	mBluetoothService=new BluetoothService(MainActivity.this,mhandler);				//������������
				    	BluetoothConnectDevice();
		            }
		        }
		    	//mBluetoothService=new BluetoothService(MainActivity.this,mhandler);				//������������
				
			}
			
		});
		ConnectTablet= (Button)findViewById(R.id.tablet);
		ConnectTablet.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub				
				mControlNetwork = new ControlNetworkService(mhandler);
				mControlNetwork.Connect(ipaddText.getText().toString(), 6666);				
			}
			
		});
		
		Debug = (Button)findViewById(R.id.button_test);
		Debug.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mControlNetwork.send_debug_info();

			}
			
		});
		
		ConnectVideo = (Button)findViewById(R.id.video);
		ConnectVideo.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				mNetwork=new NetworkService(mhandler);
				mNetwork.Connect(ipaddText.getText().toString(), 5173);
			}
			
		});
	}
	
	private final Handler mhandler = new Handler(){
		public void handleMessage(Message msg){
			switch (msg.what){
			case BLUETOOTH_GET:
				//mControlNetwork.write((byte[]) msg.obj);	
				byte[] temp = null;
				temp = (byte[]) msg.obj;
				//ipaddText.setText(new String(temp,0,msg.arg1));
				//String debugout = new String(temp,0,msg.arg1);
				//mBluetoothService.write(temp);
				mControlNetwork.write(temp);				
				break;
			case COMMAND_GET:
				mBluetoothService.write((byte[]) msg.obj);				
				break;
			case CONNECT_TO_TABLET_SUCC:
				ConnectTablet.setEnabled(false);
				break;
			case CONNECT_TO_DSP_SUCC:
				ConnectDSP.setEnabled(false);
				break;
			case VIDEO_DISCONNECT:
				Toast.makeText(MainActivity.this, "Video Disconnect from tablet, try to reconnect now.", Toast.LENGTH_SHORT).show();
				break;
			case CONNECT_TO_TABLET_VIDEO_SUCC:
				ConnectVideo.setEnabled(false);
				break;
			case CONTROL_DISCONNECT:
				Toast.makeText(MainActivity.this, "Control Disconnect from tablet, try to reconnect now.", Toast.LENGTH_SHORT).show();
				break;
			}
		}
	};
	
    private void BluetoothConnectDevice(){ 
    	if(DEBUG) Log.e(TAG, "ConnectDevice");
    	       	
    	BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(BluetoothDeviceAddress);    	
    	mBluetoothService.connect(device);
    }


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	private void initCamera(){
		if (DEBUG){
			Log.d(TAG, "initCamera");
		}		
		mSurfaceView =(SurfaceView)findViewById(R.id.VedioPriview);
		mSurfaceView.setFocusable(true);
		mSurfaceView.setFocusableInTouchMode(true);
		mSurfaceView.setClickable(true);
		mSurfaceHolder=mSurfaceView.getHolder();
		mSurfaceHolder.addCallback(this);
	}



	@Override
	public void onPictureTaken(byte[] data, Camera camera) {
		// TODO Auto-generated method stub
		
	}


	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		// TODO Auto-generated method stub
		if (DEBUG){
			Log.d(TAG, "Surface Changed");
		}		
		
		
	}


	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		if (DEBUG){
			Log.d(TAG, "Surface Created");
		}		
		mCamera= Camera.open();
		Camera.Parameters param = mCamera.getParameters();
		param.setPictureSize(640, 480);
		param.setPreviewSize(640, 480);
		//param.setPreviewFpsRange(10000, 15000);
		param.setPictureFormat(ImageFormat.JPEG);
		param.setPreviewFormat(ImageFormat.NV21);
		//List<int[]> range=param.getSupportedPreviewFpsRange();
		//param.setPreviewFpsRange(18000, 18000);
		//List list = param.getSupportedPreviewFormats();
		mCamera.setDisplayOrientation(90);		
		mCamera.setParameters(param);
		try {
			mCamera.setPreviewDisplay(mSurfaceHolder);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mCamera.setPreviewCallback(this);
		mCamera.startPreview();
		mCamera.autoFocus(null);

		

	}


	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		if (DEBUG){
			Log.d(TAG, "surfaceDestroyed");
		}		
		if(null != mCamera)
		{		
			mCamera.setPreviewCallback(null);
			mCamera.stopPreview(); 		   
			mCamera.release();  
			mCamera=null;
		}
	}


	@Override
	public void onPreviewFrame(byte[] data, Camera camera) {
		// TODO Auto-generated method stub


		if (mNetwork!=null){
			if (mNetwork.getState()==NetworkService.STATE_CONNECTED&&sendFlag%1==0){//
				YuvImage convert = new YuvImage(data,ImageFormat.NV21,camera.getParameters().getPreviewSize().width,camera.getParameters().getPreviewSize().height,null);
				ByteArrayOutputStream baos = new ByteArrayOutputStream();				
				convert.compressToJpeg(new Rect(0,0,camera.getParameters().getPreviewSize().width,camera.getParameters().getPreviewSize().height), 80, baos);
				byte[] sendbyte;
				sendbyte=baos.toByteArray();			
				byte[] sendbyte2 = new byte [4+sendbyte.length];
				System.arraycopy(i2b(sendbyte.length), 0, sendbyte2, 0, 4);
				System.arraycopy(sendbyte, 0, sendbyte2, 4, sendbyte.length);
				mNetwork.write(sendbyte2);	
				if (DEBUG){
					Log.d(TAG, "the  length:"+Integer.toString(sendbyte.length));
				}		
				sendFlag++;
			}
			else {
				sendFlag++;
			}
		}

	}
	


	
    public static byte[] i2b(int i) {  
        return new byte[]{  
                (byte) ((i >> 24) & 0xFF),  
                (byte) ((i >> 16) & 0xFF),  
                (byte) ((i >> 8) & 0xFF),  
                (byte) (i & 0xFF)  
        };  
    }  
    
}
